package com.yxy.http.util;


import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 备份
 * Created by zhaolf on 2017/3/24.
 */
public class MessageBackup {

    public static String getDirectory(String file) throws IOException {
        return getDirectory(getBaseBackupDirectory(), file);
    }




    /**
     * 取得备份根目录
     * @return
     * @throws IOException
     */
    private static String getBaseBackupDirectory() throws IOException {
        return FileUtility.getDirectory("BackupMessages", String.format("%tF", new Date(System.currentTimeMillis())));
    }



    /**
     * 创建根目录 BackupMessages-日期-Sends
     * @param baseFolder
     * @param folderName
     * @return
     * @throws IOException
     */
    private static String getDirectory(String baseFolder, String folderName) throws IOException {

        String path = baseFolder + File.separator + folderName;
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdir();
        }
        return path;
    }

    private static String getFileNameHasSuffix(String fileName) throws IOException {
        String temp = "";
        if (fileName.contains(File.separator)) {
            temp = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
        } else {
            temp = fileName.substring(0);
        }

        return temp;
    }

    private static String getFileName(String fileName) throws IOException {

        String name = fileName.substring(0, fileName.lastIndexOf('.'));
        String ext =  fileName.substring(fileName.lastIndexOf('.') + 1);

        File file = null;
        String c = "";
        while (file == null || file.exists()) {
            file = new File(name + c + "." + ext);
            if(c == "") {
                c = "0";
            } else {
                Integer ct = Integer.parseInt(c);
                ct++;
                c = ct.toString();
            }
        }
        return name + "." + ext;
    }

    /**
     * 移动文件
     *
     * @param sourFile
     * @param destFile
     * @param cover 如果目标文件存在，是否覆盖
     * @return
     */
    private static boolean moveFile(String sourFile, String destFile, boolean cover) {
        File destF = new File(destFile);
        if (destF.exists()) {
            if (!cover) {
                return false;
            }
            if (!destF.delete()) {
                return false;
            }
        }

        File sourceF = new File(sourFile);
        if (!sourceF.renameTo(destF)) {
            return false;
        }

        return true;
    }

}